package com.jing.weibo.controller.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONObject;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.DataCons;
import com.jing.system.comm.contants.StringCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.system.comm.enums.GenderType;
import com.jing.system.comm.enums.RuleType;
import com.jing.system.utils.DateUtil;
import com.jing.system.utils.PointCurrencyUtil;
import com.jing.system.utils.StringUtil;
import com.jing.weibo.pojo.info.InfoType;
import com.jing.weibo.pojo.system.Rule;
import com.jing.weibo.pojo.user.UserCwMp;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.pojo.user.UserMp;
import com.jing.weibo.service.info.InfoTypeService;
import com.jing.weibo.service.system.StationletterService;
import com.jing.weibo.service.user.UserCwMpService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.service.user.UserMpService;
import com.jing.weibo.ws.sina.FriendshipsService;
import com.jing.weibo.ws.sina.OauthService;
import com.jing.weibo.ws.sina.UserService;

/**
 * 用户登录的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class UserController extends BaseController {

	private static final Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	private OauthService oauthService;
	@Autowired
	private UserService userService;
	/*@Autowired
	private TagsService tagsService;*/
	@Autowired
	private FriendshipsService friendshipsService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserMpService userMpService;
	@Autowired
	private UserCwMpService userCwMpService;
	/*@Autowired
	private UserTagsService userTagsService;*/
	@Autowired
	private InfoTypeService infoTypeService;
	@Autowired
	private StationletterService stationletterService;

	/**
	 * 跳转到同城互粉页
	 * @return
	 */
	@RequestMapping("/mainCw")
	public String mainCw(HttpServletRequest request, ModelMap modelMap) {
		return "mainCw";
	}

	/**
	 * 跳转到粉丝管理页
	 * @return
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request, ModelMap modelMap) {
		return "main";
	}

	/**
	 * 跳转到榜上有名
	 * @return
	 */
	@RequestMapping("/mainRanking")
	public String mainRanking(HttpServletRequest request, ModelMap modelMap) {
		/*try {
			//删除历史评论信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_RANKING_COMMENT);
			//删除历史评论@信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_RANKING_AT);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}*/
		return "mainRanking";
	}

	/**
	 * 跳转到内涵信息
	 * @return
	 */
	@RequestMapping("/mainInfo")
	public String mainInfo(HttpServletRequest request, ModelMap modelMap) {
		try {
			//获取分类信息
			List<InfoType> infoTypes = infoTypeService.findAllInfoType();
			modelMap.put("infoTypes", infoTypes);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "mainInfo";
	}

	/**
	 * 跳转到泡妞吧页
	 * @return
	 */
	@RequestMapping("/mainPb")
	public String mainPb(HttpServletRequest request, ModelMap modelMap) {
		return "mainPb";
	}

	/**
	 * 跳转到个人中心页
	 * @return
	 */
	@RequestMapping("/mainCenter")
	public String mainCenter(HttpServletRequest request, ModelMap modelMap) {
		UserInfo userInfo = getSessionUser(request);
		if(userInfo != null && StringUtil.isEmpty(userInfo.getFollowing())) {
			try {
				//处理当前 用户是否关注了开发用户
				JSONObject jsonObject = friendshipsService.showFriendship(userInfo.getUsername(), WeiboCons.system_weiboId, userInfo.getToken());
				String following = jsonObject.getJSONObject("source").getString("following");
				//登录用户是否关注了开发用户
				userInfo.setFollowing(following);
				setSessionUser(request, userInfo);
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				return "redirect:index.jsp?errorCode=" + e.getErrorCode();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return "redirect:index.jsp?errorCode=error";
			}
			removeSession(request, SESSION_FORCELOGIN);
		}
		return "mainCenter";
	}

	/**
	 * 跳转到管理员页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/mainAdmin")
	public String mainAdmin(HttpServletRequest request) {
		try {
			UserInfo userInfo = getSessionUser(request);
			//不为管理员
			if(userInfo.getIsadmin().intValue() != 1) {
				logger.error(userInfo.getNickname() + ": 您不是管理员!");
				return ERROR_ADMIN;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "admin/mainAdmin";
	}

	/**
	 * 微博授权后访问的页面
	 * @param request
	 * @param modelMap
	 * @param code
	 * @return
	 */
	@RequestMapping("/weiboMain")
	public String weiboLogin(HttpServletRequest request, ModelMap modelMap, String code) {
		String result = null;
		String loginType = (String) getSession(request, SESSION_LOGIN_TYPE);
		try {
			//获取授权
			AccessToken accessToken = oauthService.getAccessTokenByCode(code);

			//获取用户信息
			User user = userService.showUserById(accessToken.getUid(), accessToken.getAccessToken());

			UserInfo userInfo = new UserInfo();
			//设置用户名为UID
			userInfo.setUsername(user.getId());
			//设置为新浪微博
			userInfo.setType(0);
			//昵称
			userInfo.setNickname(user.getScreenName());
			//性别
			userInfo.setGender(GenderType.getCodeByText(user.getGender()));
			//关注数
			userInfo.setAttentionnum(Integer.toString(user.getFriendsCount()));
			//粉丝数
			userInfo.setFansnum(Integer.toString(user.getFollowersCount()));
			//微博数
			userInfo.setWeibonum(Integer.toString(user.getStatusesCount()));
			//头像
			userInfo.setImg(user.getavatarLarge());
			//省份编码
			userInfo.setProvincecode(String.valueOf(user.getProvince()));
			//城市编码
			userInfo.setCitycode(String.valueOf(user.getCity()));
			//地址
			userInfo.setLocation(user.getLocation());
			//V认证
			userInfo.setVerified(String.valueOf(user.isVerified()));
			//授权的token
			userInfo.setToken(accessToken.getAccessToken());
			//授权到期时间
			userInfo.setAccessendtime(DateUtils.addSeconds(DateUtil.getTime(), Integer.parseInt(accessToken.getExpireIn())));

			//处理用户标签
			/*List<Tag> tags = tagsService.getTags(userInfo.getUsername(), userInfo.getToken());
			if(tags != null && tags.size() > 0) {
				StringBuffer tagBuffer = new StringBuffer();
				for (Tag tag : tags) {
					tagBuffer.append(tag.getValue()).append(",");
					//根据标签名称查询标签对象
					if(userTagsService.findByNameUserTags(tag.getValue()) == null) {
						UserTags userTags = new UserTags();
						userTags.setWeibotagid(tag.getId());
						userTags.setName(tag.getValue());
						userTags.setRemark(tag.getValue());
						userTagsService.saveUserTags(userTags);
					}
				}
				userInfo.setTags(tagBuffer.toString());
			}*/

			//判断本地数据库是否存在信息
			UserInfo ui = userInfoService.findByUserName(userInfo.getUsername());
			if(ui != null) {
				//更新用户信息
				userInfoService.updateUserInfo(userInfo);

				//修改可互粉信息
				if(ui.getIsopenmp().intValue() == 1) {
					//根据用户名查询对象
					UserMp userMp = userMpService.findByUsername(userInfo.getUsername());
					if(userMp == null) {
						//保存可互粉用户信息
						userMpService.saveUserMp(userInfo);
					}
					else if(!userInfo.getToken().equals(userMp.getToken())) {
						//根据用户名修改信息
						userMpService.updateUserMp(userInfo);
					}
				}
				//修改可同城互粉的用户
				if(ui.getIsopencitywidemp().intValue() == 1 && StringUtil.isNotEmpty(ui.getLocation())) {
					//根据用户名和token查询对象
					UserCwMp userCwMp = userCwMpService.findByUsername(userInfo.getUsername());
					if(userCwMp == null) {
						//保存可同城互粉用户信息
						userCwMpService.saveUserCwMp(userInfo);
					}
					else if(!userInfo.getToken().equals(userCwMp.getToken())) {
						//根据用户名修改信息
						userCwMpService.updateUserCwMp(userInfo);
					}
				}
			} else {
				String inviteFriendInfoUser = (String) getSession(request, SESSION_INVITEFRIENDINFO);
				PointCurrencyUtil pointCurrencyUtil = null;
				//处理邀请的用户的妞币积分信息
				if(inviteFriendInfoUser != null) {
					userInfo.setInviteuser(inviteFriendInfoUser);

					//根据用户名修改发出邀请用户的邀请总数量加1
					userInfoService.updateUserInfoInvitenum(inviteFriendInfoUser);
					pointCurrencyUtil = new PointCurrencyUtil(RuleType.TYPE_INVITE_USERS, inviteFriendInfoUser);
					pointCurrencyUtil.handlePointCurrency();
					removeSession(request, SESSION_INVITEFRIENDINFO);
				}
				//保存用户信息
				userInfoService.saveUserInfo(userInfo);

				//第一次使用该系统
				pointCurrencyUtil = new PointCurrencyUtil(RuleType.TYPE_FIRST_APPLY_SYSTEM, userInfo.getUsername());
				pointCurrencyUtil.handlePointCurrency();

				//保存可互粉用户信息
				userMpService.saveUserMp(userInfo);
				//保存可同城互粉用户信息
				userCwMpService.saveUserCwMp(userInfo);

				Rule rule = DataCons.ruleMap.get(RuleType.TYPE_FIRST_APPLY_SYSTEM.getCode());
				String content = String.format(StringCons.STATIONLETTER_FIRST_APPLY_SYSTEM_CONTENT, rule.getCurrency(), rule.getPoint());
				//发送站内信通知
				stationletterService.saveStationletter(StringCons.STATIONLETTER_FIRST_APPLY_SYSTEM_TITLE, content, userInfo.getUsername(), WeiboCons.system_weiboId, userInfo.getNickname());
			}

			//获取用户对象
			userInfo = userInfoService.findByUserName(userInfo.getUsername());

			setSessionUser(request, userInfo);

			//删除我的关注信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_ATTENTION);
			//删除我的粉丝信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_FANS);
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = getWeiboLogin(loginType, true) + e.getErrorCode();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = getWeiboLogin(loginType, true) + "error";
		}
		if(result == null) {
			result = getWeiboLogin(loginType, false);
		}
		return result;
	}

	/**
	 * 退出
	 * @param request
	 * @return
	 */
	@RequestMapping("/exit")
	public String exit(HttpServletRequest request) {
		//logger.info("进入退出!");
		try {
			UserInfo userInfo = getSessionUser(request);
			setSession(request, SESSION_FORCELOGIN, "true");
			if(userInfo != null) {
				removeSessionUser(request);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "redirect:index.jsp";
	}

	/**
	 * 用户的邀请地址
	 * @param request
	 * @param u		发出邀请的用户名
	 * @return
	 */
	@RequestMapping("/p/inviteFriendInfo")
	public String inviteFriendInfo(HttpServletRequest request, String u) {
		//将发出邀请的用户名放入Session中
		setSession(request, SESSION_INVITEFRIENDINFO, u);
		return "redirect:../index.jsp";
	}

	/**
	 * 处理跳转页面路径
	 * @param type		登录类型
	 * @param isError	是否异常跳转
	 * @return
	 */
	private String getWeiboLogin(String type, boolean isError) {
		String result = null;
		if(isError) {
			if("mobile".equals(type)) {
				result = "redirect:mobile/login.jsp?errorCode=";
			}
			else if("taobaoWeibo".equals(type)) {
				result = "redirect:taobao/taobaoWeiboLogin.jsp?errorCode=";
			}
			else {
				result = "redirect:index.jsp?errorCode=";
			}
		} else {
			if("mobile".equals(type)) {
				result = "redirect:m/main.shtml";
			}
			else if("taobaoWeibo".equals(type)) {
				result = "redirect:taobaoWeibo.thtml";
			}
			else {
				result = "redirect:mainCenter.shtml";
			}
		}
		return result;
	}
}